/**
 * int类型转换成byte二进制数据
 * @param {number} num 整数.
 * @param {number} padding 整数.
 * @returns {ByteString} 二进制数据.
 */
const intToByte = (num: number, padding = 8) => {
  let result = [];
  while (num != 0) {
    result.push(String.fromCharCode(num & 0xff));
    num >>= 8;
  }
  result = result.reverse();
  result = arrJust(result, padding);
  return result.join('');
};

/**
 * 变换数组
 * @param {ArrayBuffer} buf ArrayBuffer.
 * @returns {Array} 数组.
 */
const arrJust = (arr: Array<string>, n: number): any => {
  if (arr.length >= n) {
    arr = arr.splice(arr.length - 1 - n);
    return arr;
  } else {
    let diff = n - arr.length;
    for (let i = 0; i < diff; i++) {
      arr.unshift(String.fromCharCode(0));
    }
    return arr;
  }
};

// 获取定长补1
const fixedOne = (num: number, n: number) => {
  let len = num.toString().length;
  let numStr = num.toString();
  while (len < n) {
    numStr = '1' + num;
    len++;
  }
  return numStr;
};

export { intToByte, arrJust, fixedOne };
